using System;
using System.Xml;
using System.IO;

namespace SoftwareMonkeys.Scriptech.Projects
{
	public class ProjectConverter
	{
		public ProjectConverter ()
		{
		}
		
		public Project ConvertFromNAnt(string projectPropertiesPath)
		{
			XmlDocument document = new XmlDocument();
			document.Load(projectPropertiesPath);
			
			Project project = new Project();
			
			project.Name = GetName(document);
			
			project.GroupName = GetCompanyName(document);
			
			project.BaseNamespace = GetBaseNamespace(Path.GetDirectoryName(projectPropertiesPath));
			
			project.VirtualDirectoryName = GetVirtualDirectory(Path.GetDirectoryName(projectPropertiesPath));
			
			return project;
		}
		
		public bool IsProject(string nantFilePath)
		{
			string fileName = Path.GetFileName(nantFilePath);
			
			return fileName.ToLower().IndexOf(".project.nant") > -1;
		}
		
		private string GetName(XmlDocument document)
		{
			return GetPropertyValue(document, "Project.Name");
		}
		
		private string GetCompanyName(XmlDocument document)
		{
			return GetPropertyValue(document, "Project.CompanyName");
		}
		
		private XmlNode GetPropertyNode(XmlDocument document, string propertyName)
		{
			foreach (XmlNode node in document.DocumentElement.ChildNodes)
			{
				if (node.Name != null
				    && node.Name.ToLower() == "property"
				    && node.Attributes["name"] != null && node.Attributes["name"].Value == propertyName)
					return node;
			}
			
			return null;
		}
		
		private string GetPropertyValue(XmlDocument document, string propertyName)
		{
			string output = String.Empty;
			
			XmlNode node = GetPropertyNode(document, propertyName);
			if (node != null)
				output = node.Attributes["value"].Value;
			
			return output;
		}
		
		private string GetBaseNamespace(string projectRootPath)
		{
			return GetSolutionPropertyValue(GetSolutionPropertiesFilePath(projectRootPath),
			                                "Solution.BaseNamespace");
		}
		
		private string GetVirtualDirectory(string projectRootPath)
		{
			return GetSolutionPropertyValue(GetSolutionPropertiesFilePath(projectRootPath),
			                                "Solution.VirtualDirectory");
		}
		
		private string GetSolutionPropertyValue(string solutionFilePath, string propertyName)
		{
			string value = String.Empty;
			
			if (solutionFilePath != String.Empty)
			{
				XmlDocument doc = new XmlDocument();
				doc.Load(solutionFilePath);
				
				value = GetPropertyValue(doc, propertyName);
			}
			
			return value;
		}
		
		private string GetSolutionPropertiesFilePath(string projectRootPath)
		{
			string path = String.Empty;
			
			foreach (string file in Directory.GetFiles(projectRootPath, "*.nant", SearchOption.AllDirectories))
			{
				if (Path.GetFileName(file).ToLower().IndexOf(".solution.nant") > -1)
					path = file;
			}
			
			return path;
		}
	}
}

